package com.mymail.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mymail.entity.Receiver;

public class ReceiverDAO extends DAOImp implements DAO {

	@SuppressWarnings("unchecked")
	public ArrayList<Receiver> getReceivers(Integer mail_id) {
		String sql = "select * from `receiver` where `mail_id`=?";
		return this.findArray(sql, new Object[] { mail_id });
	}

	public boolean getByID(Integer id, Object obj) {
		Receiver rec = (Receiver) obj;
		String sql = "select * from `receiver` where `receiver_id`=?";
		return this.findOne(sql, new Object[] { id }, rec);
	}

	public boolean addNew(Object obj) {
		Receiver rec = (Receiver) obj;
		String sql = "insert into receiver (mail_id,receiver_name,"
				+ "receiver_sort) values (?,?,?)";
		String sort = new String(new char[] { rec.getSort() });
		int i = insert(sql, new Object[] { rec.getMail(), rec.getName(), sort });
		if (i > 0) {
			rec.setId(i);
			return true;
		} else {
			return false;
		}
	}

	public boolean delete(Object obj) {
		Receiver rec = (Receiver) obj;
		String sql = "delete from receiver where receiver_id=?";
		return exe(sql, new Object[] { rec.getId() });
	}

	public boolean toDatabase(Object obj) {
		Receiver rec = (Receiver) obj;
		if(rec.getId()==null){
			return addNew(rec);
		} else {
			return update(rec);
		}
	}

	public boolean update(Object obj) {
		Receiver rec = (Receiver) obj;
		String sql = "update receiver set receiver_name=?,"
				+ "receiver_sort=? where receiver_id=?";
		return exe(sql, new Object[] { rec.getMail(), rec.getName()});
	}

	protected Receiver getEntity(ResultSet result) throws SQLException {
		Receiver rec = new Receiver();
		setAtribute(result, rec);
		return rec;
	}

	protected void setAtribute(ResultSet result, Object obj)
			throws SQLException {
		Receiver rec = (Receiver) obj;
		rec.setId(result.getInt("receiver_id"));
		rec.setMail(result.getInt("mail_id"));
		rec.setName(result.getString("receiver_name"));
		rec.setSort((char) result.getString("receiver_sort").getBytes()[0]);

	}

}
